//
//  ReaderGlobalModel.m
//  ebook
//
//  Created by 吴超飞 on 16/1/15.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "ReaderGlobalModel.h"
#import "NSString+PCPaging.h"
#import <CoreText/CoreText.h>
#import "FontModel.h"

@interface ReaderGlobalModel(){
    NSArray *keys;
}

@end

static ReaderGlobalModel *model = nil;
@implementation ReaderGlobalModel

+ (instancetype)shareModel
{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        model = [[ReaderGlobalModel alloc] init];
    });
    return model;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        keys = @[@"readerConfig",@"FontSize",@"IsNight",@"BgColorType",@"LineSpace",@"PageTurnStyle",@"IsPageTransitionNoAnimate", @"fontFullname",@"orientationIsLandscape",@"autoReadingSpeed",@"phoneticReadingSpeed"];
        [self readerConfig];
    }
    
    for (NSString *key in keys) {
         [self.readerConfig addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    
    return self;
}

-(ReaderConfig *)readerConfig{
    
    if (!_readerConfig) {
        
        id data = [[NSUserDefaults standardUserDefaults] objectForKey:kReaderConfig];
        _readerConfig = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if (!_readerConfig) {
            _readerConfig = [[ReaderConfig alloc] init];
            _readerConfig.FontSize = MTReaderDefaultFontsize;
            _readerConfig.LineSpace = MTReaderDefaultLinespace;
            _readerConfig.PageTurnStyle = PageTurnStyle_Simulat;
            _readerConfig.fontFullname = @"默认字体";
            _readerConfig.BgColorType = 1;
            _readerConfig.phoneticReadingSpeed = 3;
        }
        //行间距兼容上一个版本的设置，防止出现过大的行间距，置为默认值
        if(_readerConfig.LineSpace>4)_readerConfig.LineSpace=MTReaderDefaultLinespace;
    }
    return _readerConfig;
}

-(void)saveReaderConfig{
    
    if(!_readerConfig)return;
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_readerConfig] forKey:kReaderConfig];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keys containsObject: keyPath]) {
        [self.attributes setValue:self.readerConfig.ContentTextColor forKey:NSForegroundColorAttributeName];
        [self saveReaderConfig];
    }
}

-(void)dealloc{
    
    for (NSString *key in keys) {
        [self.readerConfig removeObserver:self forKeyPath:key];
    }
}

-(UIFont *)font{
    
    NSString *fontname = _readerConfig.fontName;
    
    UIFont *font;
    if (fontname && fontname.length>0) {
        font = [UIFont fontWithName:_readerConfig.fontName size:_readerConfig.FontSize];
    } else if(_readerConfig.postScript){
        font = [self customFontWithFileName:_readerConfig.postScript Size:_readerConfig.FontSize];
    }
    
    if (!font){//没取到字体用默认字体
        font = [UIFont fontWithName:MTDefaultFont size:_readerConfig.FontSize];
    }
    
    return font;
}

-(NSMutableDictionary *)attributes{
    
    if (!_attributes) {
        _attributes = [NSMutableDictionary dictionaryWithCapacity:5];
    }
    
    [_attributes setValue:self.font forKey:NSFontAttributeName];
    [_attributes setValue:@(1.0) forKey:NSKernAttributeName];
    [_attributes setValue:self.paragraphStyle forKey:NSParagraphStyleAttributeName];
    [_attributes setValue:[ReaderGlobalModel shareModel].readerConfig.ContentTextColor forKey:NSForegroundColorAttributeName];
    return _attributes;
}

-(NSMutableParagraphStyle *)paragraphStyle{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = _readerConfig.LineSpace*0.15+0.85;//行高1倍、1.2倍、1.4倍、1.6倍
    paragraphStyle.paragraphSpacingBefore = 12*paragraphStyle.lineHeightMultiple;//段间距
    paragraphStyle.alignment = NSTextAlignmentJustified;
    //计算段落前两字的宽度，设置段前缩进
    CGSize textSize = [@"段前" sizeWithAttributes:@{NSFontAttributeName:self.font}];
    paragraphStyle.firstLineHeadIndent = textSize.width;
    paragraphStyle.headIndent = 0.0f;
    _paragraphStyle = paragraphStyle;
    
    return _paragraphStyle;
}

//计算分页数
- (NSMutableArray *)pagingText:(NSString *)text
{
    float width = [UIScreen mainScreen].bounds.size.width - [ReaderGlobalModel shareModel].readerConfig.padingLeft - [ReaderGlobalModel shareModel].readerConfig.padingRight;
    float height = [UIScreen mainScreen].bounds.size.height - [ReaderGlobalModel shareModel].readerConfig.padingTop - [ReaderGlobalModel shareModel].readerConfig.padingBottom;
    
    return [[text paginationWithAttributes:self.attributes constrainedToSize:CGSizeMake(width,height)] mutableCopy];
}

- (UIFont *)customFontWithFileName:(NSString *)fileName Size:(CGFloat)fontSize {
    
    NSString *customFontName = nil;
    NSString *fontPath = [NSString stringWithFormat:@"%@/%@/%@", PATH_OF_DOCUMENT, @"Fonts", fileName];
    NSURL *url = [NSURL fileURLWithPath:fontPath];
    
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
    [UIFont familyNames];
    CGFontRef customFont = CGFontCreateWithDataProvider(fontDataProvider);
    customFontName = (__bridge NSString *)CGFontCopyPostScriptName(customFont);
    CGDataProviderRelease(fontDataProvider);
    
    CTFontManagerRegisterGraphicsFont(customFont, NULL);
    CGFontRelease(customFont);
    
    return [UIFont fontWithName:customFontName size:fontSize];
}

@end
